package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.common.zoneOffset
import io.xxx.omni.oss.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.time.LocalDateTime
import java.util.*

@Component
class XhsClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://ark.xiaohongshu.com"

    fun execute(store: Store, path: String, request: Map<String, Any> = emptyMap()): JsonObject {
        val authorization = store.authorization
        val signMap = TreeMap(request)
        val timestamp = LocalDateTime.now().toEpochSecond(zoneOffset)
        signMap["timestamp"] = timestamp
        signMap["app-key"] = authorization["app-key"]
        val sign = DigestUtils.md5Hex(
            "${path}?${signMap.entries.joinToString("&") { "${it.key}=${it.value}" }}${authorization["app-secret"]}"
        )

        val headers = HttpHeaders()
        headers.add("timestamp", timestamp.toString())
        headers.add("app-key", authorization["app-key"])
        headers.add("sign", sign)

        val builder = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .path(path)
        request.forEach { builder.queryParam(it.key, it.value) }
        val url = builder.build(false).toUriString()
        val requestEntity = HttpEntity(null, headers)
        return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String::class.java).body!!.toJsonObject()
    }
}